<template>
	<view>
		<view class="search-bar">
      <uni-search-bar  cancelButton="none" @clear="searchResults=[]" @input="input" />
    </view>
    <!-- 搜索建议 -->
    <uni-list v-if="searchResults.length" >
      <uni-list-item @click="goDetail(item.goods_id)" :clickable="true" :key="item.goods_id" v-for="item in searchResults" :showArrow="true" :ellipsis="2"  :title="item.goods_name"></uni-list-item>
    </uni-list>
    <!-- 搜索历史 -->
    <view v-else class="history-box">
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" @click="cleanHistory" size="17"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag @click="gotoGoodsList(item)" :text="item" v-for="(item, i) in historyList" :key="i"></uni-tag>
      </view>
    </view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				 // 延时器的 timerId
        timer: null,
        // 搜索关键词
        kw: '',
        // 搜索结果列表
        searchResults: [],
       // 搜索关键词的历史记录
        historyList: JSON.parse(uni.getStorageSync('kw') || '[]')
			};
		},
    methods: {
      input(event) {
         // 清楚定时器
         clearTimeout(this.timer)
         // 重新启动一个延时器，并把 timerId 赋值给 this.timer
         this.timer = setTimeout(()=>{
           this.kw = event.value
           this.getSearchList()
         },200)
      },
      // 获取搜索建议列表
      async getSearchList(){
        if(!this.kw) return false
        // 有值就放入存储起来历史记录
        let idx = this.historyList.findIndex(item=>item===this.kw)
        if(idx!==-1) this.historyList.splice(idx,1)
        this.historyList.unshift(this.kw)
        uni.setStorageSync('kw', JSON.stringify(this.historyList))
        // 1. 发送请去
        const { data:res } = await uni.$http.get('/api/public/v1/goods/qsearch', { query: this.kw })
        // 2. 错误处理
        if(res.meta.status !==200) return uni.$showMsg()
        // 3. 成功赋值
        this.searchResults = res.message 
      },
      // 跳转到商品详情
      goDetail(id){
        console.log(id);
        uni.navigateTo({
          url:'/subpkg/goods-detail/goods-detail?id='+id
        })
      },
      // 清空搜索历史
      cleanHistory(){
        this.historyList = []
         uni.setStorageSync('kw', JSON.stringify(this.historyList))
      },
      // 搜索历史点击跳转到商品列表页面
      // 点击跳转到商品列表页面
      gotoGoodsList(kw) {
        uni.navigateTo({
          url: '/subpkg/goods_list/goods_list?query=' + kw
        })
      }
    },
	}
</script>

<style lang="scss">
.search-bar{
  position: sticky;
  top: 0;
  z-index: 10;
}
.history-box {
  padding: 0 5px;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    .uni-tag {
      margin-top: 5px;
      margin-right: 5px;
    }
  }
}
</style>
